package com.s.rpc.core;

import com.s.rpc.ServiceRegistry;
import com.s.rpc.channel.ServerChannel;
import com.s.rpc.serializer.Serializer;
import com.s.rpc.exception.RpcException;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.Data;

/**
 * @author ShenshenLuo
 * @email luoshenshen@buaa.edu.cn
 * @date 2025/5/11 13:40
 **/
@Data
public class NettyServer {

    private int port;

    private String host;

    private Serializer serializer;

    private ServiceRegistry serviceRegistry;

    public NettyServer() {
    }

    public NettyServer(String host, int port, Serializer serializer) {
        this.host = host;
        this.port = port;
        this.serializer = serializer;
        this.serviceRegistry = new ServiceRegistry();
    }

    public void registerService(Object service) {
        serviceRegistry.register(service);
    }

    @SuppressWarnings("all")
    public void startServer() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new ServerChannel(serializer, serviceRegistry));

            ChannelFuture future = bootstrap.bind(host, port).sync();
            System.out.println("Server started on " + host + ":" + port);
            future.channel().closeFuture().sync();
        } catch (Exception e){
            throw new RpcException("Netty server error");
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}
